﻿@page "/groups/{id}/{action}"
@inherits Fluxor.Blazor.Web.Components.FluxorLayout
@using Microsoft.EntityFrameworkCore;
@using SimpleIdServer.IdServer.Api.Groups
@using SimpleIdServer.IdServer.Stores;
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.GroupStore;
@using SimpleIdServer.IdServer.Website.Stores.RealmStore;
@layout MainLayout
@inject DialogService dialogService
@inject NavigationManager navigationManager
@inject NotificationService notificationService
@inject IDispatcher dispatcher
@inject IGroupService groupService
@inject IState<GroupState> groupState
@inject IState<GroupHierarchyState> groupHierarchyState
@inject IUrlHelper urlHelper

<SidAuthorizeView Roles=@("/groups/manage,/groups/view")>
    <Authorized>
        <RadzenBreadCrumb>
            <RadzenBreadCrumbItem Path="@urlHelper.GetUrl("/groups")" Text="@Global.Groups" />
            <RadzenBreadCrumbItem Text="@Global.GroupDetails" />
        </RadzenBreadCrumb>

        <RadzenText class="mt-3 mb-3 no-margin" Text="@groupState.Value.Group?.Name" TextStyle="TextStyle.DisplayH3" />

        <RadzenBreadCrumb>
            @foreach (var groupName in groupNames)
            {
                <RadzenBreadCrumbItem Text="@groupName" />
            }
        </RadzenBreadCrumb>

        <RadzenCardLoader Variant="Variant.Filled" IsLoading=@groupState.Value.IsLoading>
            <RadzenSplitter>
                <RadzenSplitterPane Size="10%">
                    @if (!isLoading)
                    {
                        <RadzenTree Data=@groups>
                            <RadzenTreeLevel Selected="@(o => IsSelected(o))" Expanded="@(o => IsExpanded(o))" HasChildren="@(o => HasChildren(o))" TextProperty="Name" ChildrenProperty="Children">
                                <Template>
                                    <RadzenLink Text="@GetGroupName(context)" Path="@GetGroupLink(context)" />
                                </Template>
                            </RadzenTreeLevel>
                        </RadzenTree>
                    }
                </RadzenSplitterPane>
                <RadzenSplitterPane>
                    <div class="ml-3">
                        <RadzenTabs Change=@OnChange @bind-SelectedIndex="selectedIndex">
                            <Tabs>
                                <RadzenTabsItem Text="@Global.Children">
                                    <GroupChildren Group="@groupState.Value.Group"></GroupChildren>
                                </RadzenTabsItem>
                                <RadzenTabsItem Text="@Global.Roles">
                                    <GroupRoles Group="@groupState.Value.Group"></GroupRoles>
                                </RadzenTabsItem>
                            </Tabs>
                        </RadzenTabs>
                    </div>
                </RadzenSplitterPane>
            </RadzenSplitter>
        </RadzenCardLoader>
    </Authorized>
    <NotAuthorized>
        @Global.NotAuthorized
    </NotAuthorized>
</SidAuthorizeView>

@code {
    bool isLoading = true;
    Domains.Group currentGroup;
    List<GetHierarchicalGroupResult> groups;
    Dictionary<string, int> mappingActionNameToIndex = new Dictionary<string, int>
    {
        { "children", 0 },
        { "roles", 1 }
    };

    [Parameter]
    public string id { get; set; } = null!;

    [Parameter]
    public string? action { get; set; } = null;

    public List<string> groupNames = new List<string>();

    int selectedIndex = 0;

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if(firstRender)
        {
            SubscribeToAction<GetGroupSuccessAction>((act) =>
            {
                currentGroup = act.Group;
                groupNames = currentGroup.FullPath.Split('.').ToList();
                dispatcher.Dispatch(new GetHierarchicalGroupAction { GroupId = act.RootGroup.Id });
            });
            SubscribeToAction<GetHierarchicalGroupAction>((act) =>
            {
                isLoading = true;
            });
            SubscribeToAction<GetHierarchicalGroupSuccessAction>((act) =>
            {
                isLoading = false;
                groups = act.Result;
            });
            SubscribeToAction<AddGroupSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.GroupMemberAdded });
                dialogService.Close();
                groups.First().Resolve(currentGroup.FullPath).Children.Add(new GetHierarchicalGroupResult
                {
                    Root = new Domains.Group
                    {
                        Id = act.Id,
                        Name = act.Name,
                        FullPath = act.FullPath,
                        Description = act.Description
                    }
                });
                StateHasChanged();
            });
            SubscribeToAction<RemoveSelectedGroupsSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.GroupMembersRemoved });
                var rootGroup = groups.First().Resolve(currentGroup.FullPath);
                rootGroup.Children = rootGroup.Children.Where(c => !act.FullPathLst.Contains(c.Root.FullPath)).ToList();
                StateHasChanged();
            });
            SubscribeToAction<RemoveSelectedGroupRolesSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.GroupRolesRemoved });
            });
        }
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (string.IsNullOrWhiteSpace(id)) return;
        if (!string.IsNullOrWhiteSpace(action) && mappingActionNameToIndex.ContainsKey(action))
            selectedIndex = mappingActionNameToIndex[action];
        SubscribeToAction<GetGroupFailureAction>((act) =>
        {
            notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = act.ErrorMessage });
            StateHasChanged();
        });
        dispatcher.Dispatch(new GetGroupAction { Id = id });
    }

    void OnChange(int index)
    {
        var rec = mappingActionNameToIndex.Single(kvp => kvp.Value == index);
        navigationManager.NavigateTo(urlHelper.GetUrl($"/groups/{id}/{rec.Key}"));
    }

    string GetGroupName(RadzenTreeItem data)
    {
        return (data.Value as GetHierarchicalGroupResult).Name;
    }

    string GetGroupLink(RadzenTreeItem data)
    {
        return urlHelper.GetUrl(urlHelper.GetUrl($"/groups/{(data.Value as GetHierarchicalGroupResult).Root.Id}/children"));
    }

    bool HasChildren(object data)
    {
        var record = data as GetHierarchicalGroupResult;
        return record.Children == null ? false : record.Children.Any();
    }

    bool IsExpanded(object data)
    {
        var record = data as GetHierarchicalGroupResult;
        var fp = record.Root.FullPath;
        return record.Root.GetLevel() < currentGroup.GetLevel() &&
            currentGroup.FullPath.StartsWith(record.Root.FullPath);
    }

    bool IsSelected(object data)
    {        
        var record = data as GetHierarchicalGroupResult;
        return record.Root.FullPath == currentGroup.FullPath;
    }
}